
import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../http/api.dart';
import '../main.dart';
import '../util/toast_util.dart';
import 'index_page.dart';
import 'setting_common_page.dart';


class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {

  String _username = '';
  String _psw = '';
  RxBool check = RxBool(false);

  @override
  initState() {
    super.initState();
    if(settingEntity.rememberPaw != null){
      check.value = settingEntity.rememberPaw!;
      if(check.value){
        if(settingEntity.username != null){
          _username = settingEntity.username!;
        }
        if(settingEntity.psw != null){
          _psw = settingEntity.psw!;
        }
      }
    }


  }

  _accountWidget(){
    return Container(
      width: 176.w,
      decoration:BoxDecoration(
        border: Border.all(color: Colors.grey,width: 0.5.r),
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      padding: EdgeInsets.only(left:4.w,right: 4.w),
      margin:  EdgeInsets.only(bottom: 5.h,top: 5.h),
      child: Row(
        children: [
          const Icon(Icons.person_outline_rounded),
          SizedBox(width: 4.w,),
          Container(
            width: 150.w,
            child: TextField(
                minLines: 1,
                textInputAction: TextInputAction.search,
                onChanged: (input){
                  _username = input;
                },
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(top: 10.h,bottom: 10.h),
                  isCollapsed: true,
                  hintText: "请输入管理员账号",
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey,fontSize: 10.sp)
                ),
                style: TextStyle(color: Colors.black,fontSize: 10.sp),
                controller: TextEditingController.fromValue(TextEditingValue(
                    text: _username,
                    selection: TextSelection.fromPosition(
                        TextPosition(
                            affinity: TextAffinity.downstream,
                            offset: _username.length))
                )),
            ),

          ),
        ],
      )
    );
  }

  RxBool passwordVisible = RxBool(false);

  _passwordWidget(){
    return Container(
        width: 176.w,
        decoration:BoxDecoration(
          border: Border.all(color: Colors.grey,width: 0.5.r),
          borderRadius: BorderRadius.all(Radius.circular(4.r)),
        ),
        padding: EdgeInsets.only(left:4.w),
        margin:  EdgeInsets.only(bottom: 5.h,top: 5.h),
        child: Obx(() => Row(
          children: [
            const Icon(Icons.lock_outline),
            SizedBox(width: 4.w,),
            Container(
              width: 135.w,
              child: TextField(
                  obscureText: !passwordVisible.value,
                  minLines: 1,
                  textInputAction: TextInputAction.search,
                  onChanged: (input){
                    _psw = input;
                  },
                  decoration: InputDecoration(
                      contentPadding: EdgeInsets.only(top: 10.h,bottom: 10.h),
                      isCollapsed: true,
                      hintText: "请输入密码",
                      border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey,fontSize: 10.sp)
                  ),
                  style: TextStyle(color: Colors.black,fontSize: 10.sp),
                  controller: TextEditingController.fromValue(TextEditingValue(
                      text: _psw,
                      selection: TextSelection.fromPosition(
                          TextPosition(
                              affinity: TextAffinity.downstream,
                              offset: _psw.length))
                  )),
              ),
            ),
            SizedBox(width: 4.w,),
            InkWell(
              onTap: (){
                passwordVisible.value = !passwordVisible.value;
              },
              child: Icon(passwordVisible.value?Icons.remove_red_eye:Icons.remove_red_eye_outlined),
            )
          ],
        ))
    );
  }


  _rememberPasswordWidget(){
    return Obx(() => Row(
      children: [
        Checkbox(
         value: check.value,
         onChanged: (value){
           check.value = !check.value;
           settingEntity.rememberPaw = check.value;
         }
        ),
        Text("记住密码",style: TextStyle(fontSize: 8.sp),)
      ],
    ));
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            SizedBox(height: 10.h,),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                InkWell(
                  onTap: (){
                    Get.to(()=>const SettingCommon());
                  },
                  child:Image.asset("assets/images/setting.png",width: 30.w,fit: BoxFit.fitWidth,),
                ),
                const Text('      ')
              ],
            ),
            SizedBox(height: 10.h,),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Stack(
                  alignment: AlignmentDirectional.center,
                  children: [
                    Image.asset("assets/images/login_left.png",height: 300.h,fit: BoxFit.fitHeight,),

                    Positioned(
                        top: 120.h,
                        child: _accountWidget()
                    ),
                    Positioned(
                        top: 160.h,
                        child: _passwordWidget()
                    ),
                    Positioned(
                        left: 8.w,
                        top: 198.h,
                        child: _rememberPasswordWidget()
                    ),
                    Positioned(
                        top: 230.h,
                        child: InkWell(
                          onTap: () async {
                            if(_username.isEmpty){
                              toastWarn('管理员账号不能为空');
                              return;
                            }
                            if(_psw.isEmpty){
                              toastWarn('密码不能为空');
                              return;
                            }
                            BotToast.showLoading();
                            var result = await login(_username, _toMd5(_psw));
                            BotToast.closeAllLoading();
                            if(result != null){
                              if(check.value){
                                settingEntity.username = _username;
                                settingEntity.psw = _psw;
                              }else{
                                settingEntity.username = null;
                                settingEntity.psw = null;
                              }
                              final box = GetStorage();
                              box.write('setting_entity', settingEntity.toJson());
                              currentTask.uid = result;
                              Get.off(()=> const Index());
                            }
                          },
                          child:Image.asset("assets/images/login.png",width: 176.w,fit: BoxFit.fitWidth,),
                        )
                    ),
                  ],
                ),
                Image.asset("assets/images/login_right.png",height: 300.h,fit: BoxFit.fitHeight,),
              ],
            )
          ],
        )
      ),
    );
  }

  String _toMd5(String data) {
    var content = const Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString().toUpperCase();
  }
}